package com.junxian.demo02.exception;

import com.junxian.demo02.dao.ErrorInfo;
import com.junxian.demo02.dao.User;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by admin on 2018/12/5.
 */
@ControllerAdvice
public class GlobalExceptionHandler {  //ModelAndView?
    @ExceptionHandler(value = Exception.class)//只要是Exception的错误都会转到这里
    public ModelAndView defaultErrorHandler(HttpServletRequest request , Exception e) throws Exception{
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception" , e);
        modelAndView.addObject("url" , request.getRequestURL());
        modelAndView.setViewName("error");
        return modelAndView;
    }

    @ExceptionHandler(value = MyException.class)//只要是MyException的报错都会转到这里
    @ResponseBody //转化为JSON串
    public ErrorInfo<String> jsonErrorHandler(HttpServletRequest httpServletRequest , Exception e) throws Exception{
        //创建统一的JSON返回对象，code：消息类型，message：消息内容，url：请求的url，data：请求返回的数据
        ErrorInfo<String> errorInfo = new ErrorInfo<>();
        errorInfo.setMessage(e.getMessage());
        errorInfo.setCode(ErrorInfo.OK);
        errorInfo.setData("Success!");
        errorInfo.setUrl(httpServletRequest.getRequestURI().toString());
        return errorInfo;
    }

    @ExceptionHandler(value = MyException01.class)//只要是MyException01的报错都会转到这里
    @ResponseBody //转化为JSON串
    public User jsonErrorHandler01(HttpServletRequest httpServletRequest , Exception e) throws Exception{
        User user = new User();
        user.setUserName(e.getMessage());
        user.setBirthDay("2018-12-12");
        return user;
    }
}
